<?php
class AclHelper
{
	/**
	 * 检查用户访问资源的权限|User Access Node
	 */
	public static function check_uan($user_id, $access, $node_id)
	{
		//Get Virtual User Role ID
		$u_role_id	=	User::instance()->getVirtualRoleId($user_id);

		//User (1:N) Role
		$roles	=	Db::get('AclUr')
						->select('role_id')
						->where(array('user_id'=>$user_id))
						->getCols();
		$role_link	=	$roles ? join(',', $roles) : '';

		//Get Node.
		$node	=	Db::get('Node')
						->select(array('link','mode','exptime'))
						->where(array('node_id'=>$node_id))
						->getOne();

		//Get node link path ordered.
		$node_link	=	$node_id;
		if($node['link']) {
			$node_link	=	join(',', array_reverse(explode(',', "{$node['link']},{$node_id}")));
		}

		$ran	=	Db::get('AclRan')
						->select(array('node_id','role_id','signal'))
						->where("node_id IN ({$node_link})", "role_id IN ({$role_link})", array('access'=>$access))
						->getAll();
		$acl	=	array();
		foreach($ran as $r)
		{
			$acl[$r['node_id']][$r['role_id']]	=	$r['signal'];
		}
		foreach($acl as $nid=>$row)
		{
			if(isset($row[$u_role_id])) {
				return '1'==$row[$u_role_id];
			}
			return in_array('1', $row);
		}

		return false;
	}

	/**
	 * 添加角色操作资源的权限规则|Role Access Node
	 */
	public static function fill_ran($role_id, $access, $node_id, $signal=1)
	{
		$data	=	array(
			'role_id'	=>	$role_id,
			'access'	=>	$access,
			'node_id'	=>	$node_id,
		);
		$ran	=	Db::get('AclRan');

		//Role,Access,Node唯一
		if($ran->count()->where($data)->getCol() >0)
		{
			return $ran->update(array('signal'=>$signal))->where($data)->exec();
		}
		else
		{
			$data['signal']	=	$signal;
			return $ran->insert($data)->exec();
		}
	}

	/**
	 * 添加用户操作资源的权限规则。会转换用户为角色。
	 */
	public static function fill_uan($user_id, $access, $node_id, $signal=1)
	{
		$role_id	=	User::instance()->getVirtualRoleId($user_id);
		if(!$role_id) {
			return false;
		}
		return self::fill_ran($role_id, $access, $node_id, $signal);
	}

	/**
	 * 添加组操作资源的权限规则。
	 */
	public static function fill_gan($group_id, $access, $node_id, $signal=1)
	{
		$role_id	=	Group::instance()->getVirtualRoleId($group_id);
		if(!$role_id) {
			return false;
		}
		return self::fill_ran($role_id, $access, $node_id, $signal);
	}

}
?>